package com.yz.javaagent.core.option;

import com.sun.tools.attach.*;
import com.sun.tools.javac.util.Assert;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PIDService {

    private String agentJarPath ="/Users/shanchong/work/project/javaagent/agent/target/java-agent.jar";

    public static String coreJatPath = "/Users/shanchong/work/project/javaagent/core/target/core-jar-with-dependencies.jar";

    public Map<String, String> pids(){
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        Map<String, String> map = list.stream().collect(Collectors.toMap(VirtualMachineDescriptor::id, VirtualMachineDescriptor::displayName));
        return map;
    }

    public void attach(String pid,String args) {
        Assert.checkNonNull(pid);
        try {
            VirtualMachine virtualMachine = VirtualMachine.attach(pid);
            virtualMachine.loadAgent(agentJarPath,coreJatPath+","+args);
            virtualMachine.detach();
        } catch (AttachNotSupportedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AgentLoadException e) {
            e.printStackTrace();
        } catch (AgentInitializationException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        PIDService pidService = new PIDService();
        Map<String, String> pids = pidService.pids();
        pids.forEach((k,v)->{
            if (v.endsWith("AsmDemo")){
                pidService.attach(k,"com.yz.javaagent.demo.DemoMain,println");
                return;
            }
        });
    }
}
